/**
 * User: aOmMiez
 * Date: 3/25/13 AD
 * Time: 1:40 PM
 * NodJs Helper
 */

var config = require(__dirname + '/config.js');
var crypto = require("crypto");
var libCore = require(__dirname + "/lib/libCore");
var microtime = require('microtime');
var mysql = require("mysql");
var helper = {}

// Setup Mysql
var connection = mysql.createConnection({
    host: config.mysql.host,
    port: config.mysql.port,
    user: config.mysql.user,
    password: config.mysql.pass,
    database: config.mysql.db
});

connection.connect(function (error) {
    if (error) {
        return console.log('CONNECTION error: ' + error);
    }
    connection.query('USE ' + config.mysql.db);
});
/*
 * Password Encode Base64 & Sha1
 */

helper.hasPass = function (pass) {
    return crypto.createHash('sha1').update(pass).digest('base64');
};

/*
 * Gen Token
 */

helper.getToken = function () {

    libCore.mt_rand(0, microtime.nowDouble() * 1000000);

    // Array of characters, adjust as desired
    var chars = [
        'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',
        'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',
        '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',
        'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',
        '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',
        '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',
        'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'
    ]

    // Array indice friendly number of chars; empty token string
    var numChars = chars.length - 1;
    var token = '';

    // Create random token at the specified length
    for (var i = 0; i < 32; i++) {
        token += chars[libCore.mt_rand(0, numChars)];
    }

    // Number of 32 char chunks
    var chunks = Math.ceil(token.length / 32);
    var md5token = '';

    // Run each chunk through md5
    for (var i = 1; i <= chunks; i++) {

        md5token += crypto.createHash('md5').update(token.substr(i * 32 - 32, 32)).digest("hex");
    }

    // Trim the token
    token = md5token.substr(0, 32);

    return token;

}

/*
 * Check User id
 */

helper.checkUserId = function (id) {
    var result = true;
    connection.query('SELECT count(id) as countId FROM Account where id = "' + id + '"', function (err, res, fie) {
        if (err) {
            return console.log('error: ' + err);
        } else {
            if (res.length > 0) {
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}

/*
 * Check Site id
 */

helper.checkSiteId = function (id) {
    var result = true;

    connection.query('SELECT count(id) as countId FROM Site where id = "' + id + '"', function (err, res, fie) {
        if (err) {
            return console.log('error: ' + err);
        } else {
            if (res.length > 0) {
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}

/*
 *  Check Owner Place
 */

helper.checkOwnerPlace = function (userId,siteId) {
    var result = true;
    connection.query('SELECT count(id) as countId FROM Place where id = "' + siteId + '" and createById = "' + userId + '" ', function (err, res, fie) {
        if (err) {
            return console.log('error: ' + err);
        } else {
            if (res.length > 0) {
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}

module.exports = helper;